package thread;

import bean.util.WindowUtil;
import controller.RobotController;

public class AutoWarThread extends Thread implements Runnable {

	private RobotController rbCtrl = null;

	private boolean canDef = false;

	public AutoWarThread(boolean canDef) {
		if (WindowUtil.cgWins.size() > 0) {
			rbCtrl = new RobotController(WindowUtil.cgWins.get(0));
		}

		this.canDef = canDef;
	}

	public void run() {
		int oddNumber = 0;
		int lastPosition = 0;
		boolean isFirstAction = false;

		while (true) {
			if (ThreadToggle.KEEP_RUNNING) {
				int gameStatus = rbCtrl.getGameStatus();

				switch (gameStatus) {
				case RobotController.NORMAL_STATUS:
					rbCtrl.setConnect();
					oddNumber = 1 - oddNumber;
					isFirstAction = true;

					rbCtrl.delay(200);
					rbCtrl.moveOnMap(RobotController.NO_DIRECTION, true);
					rbCtrl.delay(500);

					if (oddNumber == 0) {
						rbCtrl.moveOnMap(RobotController.LEFT_DIRECTION, true);
					} else {
						rbCtrl.moveOnMap(RobotController.RIGHT_DIRECTION, true);
					}

					rbCtrl.delay(1000);
					break;
				case RobotController.ROLE_WAR_STATUS:
					if (canDef && isFirstAction) {
						rbCtrl.roleActionSelect(RobotController.DEF_ACTION);
					} else {
						rbCtrl.roleActionSelect(RobotController.ATK_ACTION);
						lastPosition = hitEverywhere(gameStatus);
					}

					isFirstAction = false;
					break;
				case RobotController.PET_WAR_STATUS:
					if (lastPosition != -1) {
						rbCtrl.hitEnemyOnPosition(lastPosition);
					} else {
						hitEverywhere(gameStatus);
					}

					lastPosition = -1;
					break;
				case RobotController.UNCONNECTED_STATUS:
					rbCtrl.reconnected();

					break;
				default:
					break;
				}
			}

			rbCtrl.delay(500);
		}
	}

	private int hitEverywhere(int gameStatus) {
		int position = -1;

		for (int i = 0; i < 10; i++) {
			rbCtrl.hitEnemyOnPosition(i);
			if (gameStatus != rbCtrl.getGameStatus()) {
				position = i;
				break;
			}
		}

		return position;
	}
}
